/**
 * 
 */
package de.idgard.android.addon.js;

import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.util.Log;
import android.webkit.JsPromptResult;
import de.idgard.android.R;
import de.idgard.android.addon.services.ContextAware;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.dialogs.IDGPrivacyConnectLoginDialog;
import de.idgard.android.addon.ui.dialogs.IDGPrivacyConnectSaveDialog;
import de.idgard.android.addon.ui.services.BrowserUtilityService;
import de.idgard.android.addon.ui.services.dto.FieldDTO;
import de.idgard.json.IDGGson;
import de.idgard.json.response.PrivacyProfilesResponse;
import de.idgard.json.transport.Receiver;
import de.idgard.webapp.shared.dto.profile.SimpleProfileDto;

/**
 * 
 * @author <a href="mailto:vesko.georgiev@uniscon.com">Vesko Georgiev</a>
 */
public class PrivacyConnect implements ContextAware {
	private String separator = GlobalServiceRegistry.instance().getPropertiesService().getString(R.string.js_value_separator);

	private Context context;
	private OneClickLoginDescriptor oneClick;

	@Override
	public void setContext(Context ctx) {
		this.context = ctx;
	}

	private boolean enableOneClickLogin() {
		return oneClick != null;
	}

	private BrowserUtilityService getBrowserUtilityService() {
		return GlobalServiceRegistry.instance().getBrowserUtilityService();
	}

	public void selectProfile(String defaultValue, final JsPromptResult jsPrompt) {
		String host = defaultValue;

		GlobalServiceRegistry.instance().getBackendService().getPrivacyConnectProfiles(host).fire(new Receiver<PrivacyProfilesResponse>() {
			@Override
			public void onSuccess(PrivacyProfilesResponse response) {
				if (response.size() == 0) {
					jsPrompt.confirm(ProfileSelection.empty().toString());
					return;
				}

				if (oneClick != null) {
					for (final SimpleProfileDto p : response) {
						if (oneClick.getPid().equals(p.getId())) {
							GlobalServiceRegistry.instance().getBackendService().getPrivacyConnectProfileToken(p.getId()).fire(new Receiver<String>() {
								@Override
								public void onSuccess(String token) {
									jsPrompt.confirm(ProfileSelection.selected(p.getUsername(), token).toString());
								}

								@Override
								public void onFailure(int code, String response) {
									jsPrompt.confirm(ProfileSelection.cancel().toString());
								}

								@Override
								public void onException(Exception e) {
									jsPrompt.confirm(ProfileSelection.cancel().toString());
								}
							});
							return;
						}
					}
					jsPrompt.confirm(ProfileSelection.empty().toString());
				} else {
					final IDGPrivacyConnectLoginDialog pcDialog = new IDGPrivacyConnectLoginDialog(context, response);
					pcDialog.setOnDismissListener(new OnDismissListener() {
						@Override
						public void onDismiss(DialogInterface dialog) {
							ProfileSelection ps = pcDialog.getSelection();
							getBrowserUtilityService().updateWebViewUserAgentStringWithProfileInfo(ps.getToken(), new FieldDTO(null, "pass", null));
							jsPrompt.confirm(ps.toString());
						}
					});
					pcDialog.show();
				}
			}

			@Override
			public void onFailure(int code, String response) {
				jsPrompt.confirm(ProfileSelection.error().toString());
			}

			@Override
			public void onException(Exception e) {
				jsPrompt.confirm(ProfileSelection.error().toString());
			}
		});
	}

	public void formWillSubmit(String defaultValue, JsPromptResult result) {
		String[] parts = defaultValue.split(separator);
		String agentString = getBrowserUtilityService().updateWebViewUserAgentStringWithProfileInfo(parts[0], new FieldDTO(null, parts[1], null));
		Log.d(getClass().getName(), agentString);
		result.confirm();
	}

	public void isOneClickEnabled(JsPromptResult result) {
		result.confirm(Boolean.toString(enableOneClickLogin()));
		oneClick = null;
	}

	public void enableOneClickLogin(String defaultValue, JsPromptResult result) {
		this.oneClick = IDGGson.gson().fromJson(defaultValue, OneClickLoginDescriptor.class);
		result.confirm();
	}

	public void saveProfile(String defaultValue, JsPromptResult result) {
		try {
			SimpleProfileDto profile = IDGGson.gson().fromJson(defaultValue, SimpleProfileDto.class);
			if (checkProfileValidity(profile)) {
				new IDGPrivacyConnectSaveDialog(context, result, profile).show();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private boolean checkProfileValidity(SimpleProfileDto profile) {
		try {
			new URL(profile.getFormUrl());
			return true;
		} catch (MalformedURLException e) {
			return false;
		}
	}
}
